package compilator4urbi.actions.generate;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;

import behaviourdiagram.Behaviour;
import behaviourdiagram.Mission;

import compilator4urbi.exceptions.InvalidFSMException;
import compilator4urbi.util.BehaviourDiagramSerializer;

import fsm.FSM;

public class MissionBuilder {

	private IFile missionLocation;
	
	private Mission mission;

	public MissionBuilder(IFile missionLocationPath) {
		this.missionLocation = missionLocationPath;
	}

	public Mission getMission() {
		return mission;
	}
	
	public IFile getMissionLocationPath() {
		return missionLocation;
	}

	private void loadMission() {
		File file = new File(missionLocation.getLocation().toOSString());
		mission = BehaviourDiagramSerializer.load(file);
	}
	
	private FSM loadFSM(String name) {
		IPath path = Path.fromPortableString(name + ".fsm.xmi");
		IFile ifile = missionLocation.getParent().getFile(path);
		if (ifile == null)
			return null;
		File file = new File(ifile.getLocation().toOSString());
		FSM fsm = BehaviourDiagramSerializer.loadFSM(file);
		try {
			fsm.check();
		} catch (Exception e) {
			return null;
		}
		return fsm;
	}
	
	public void build () throws InvalidFSMException {
		loadMission();
		for (Behaviour behaviour : mission.getBehaviours()) {
			FSM fsm = loadFSM(behaviour.getName());
			if (fsm == null)
				throw new InvalidFSMException(behaviour.getName());
			behaviour.setRepresentedBy(fsm);
		}
	}
	
}
